package com.shujushow.common.security;

import com.shujushow.common.constants.Constants;
import com.shujushow.common.session.ShiroSession;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionContext;
import org.apache.shiro.session.mgt.SessionFactory;
import org.apache.shiro.web.session.mgt.WebSessionContext;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by xinshu on 2016/5/19.
 */
public class ShiroSessionFactory implements SessionFactory {

    public Session createSession(SessionContext initData) {

        if (initData != null) {
            String host = initData.getHost();
            String hostName = "";
            WebSessionContext sessionContext = (WebSessionContext) initData;
            HttpServletRequest request = (HttpServletRequest) sessionContext.getServletRequest();

            if (host != null) {
                String userAgent = null;
                if (request != null) {
                    userAgent = request.getHeader("User-Agent");
                    host = getIpAddr(request);
                    hostName = getHostName(host);
                }
                ShiroSession session = new ShiroSession(host);
                session.setAttribute(Constants.SessionKey.USER_AGENT_KEY, userAgent);
                session.setAttribute(Constants.SessionKey.HOST_NAME_KEY, hostName);
                return session;
            }
        }

        return new ShiroSession();

    }


    String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (null != ip && !"".equals(ip.trim()) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        ip = request.getHeader("X-Forwarded-For");
        if (null != ip && !"".equals(ip.trim()) && !"unknown".equalsIgnoreCase(ip)) {
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }

        }

        return request.getRemoteAddr();
    }

    String getHostName(String ip) {
        InetAddress inetAddress;
        String hostName = "";
        try {
            if (Constants.Adress.LOCAL.equals(ip)
                    || Constants.Adress.LOCAL_IPV6.equals(ip)) {
                inetAddress = InetAddress.getLocalHost();
            } else {
                inetAddress = InetAddress.getByName(ip);
            }

            hostName = inetAddress.getHostName();

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return hostName;
    }

}
